package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    // 微信登录接口地址
    public static final String WECHAT_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    /**
     * 微信登录
     *
     * @param userLoginDTO 微信登录数据 -- 授权码
     * @return 用户对象
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // ①调用微信接口，根据授权码, 获取微信用户的唯一标识openid
        String openid = getOpenid(userLoginDTO.getCode());

        // ②判断openid是否为空, 如果为空，则抛出登录失败异常
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // ③根据openid查询数据库获取微信用户
        User user = userMapper.getByOpenid(openid);
        // ④如果是新用户，在数据库中完成注册
        if (user == null) {
            user = User.builder().openid(openid).createTime(LocalDateTime.now()).build(); // 创建用户对象 -- 目前仅能保存openid和创建时间
            userMapper.insert(user);
        }

        // ⑤返回用户对象
        return user;
    }

    /**
     * 调用微信接口，根据授权码, 获取微信用户的唯一标识openid --> Ctrl + Alt + M 抽取方法
     *
     * @param code 微信登录授权码
     * @return 微信用户的唯一标识openid
     */
    private String getOpenid(String code) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WECHAT_LOGIN_URL, paramMap); // 服务端调用微信接口，得到JSON串(其中包括openid)

        JSONObject jsonObject = JSON.parseObject(json);
        return jsonObject.getString("openid");
    }
}
